var $j = jQuery.noConflict(true);
jQuery = $j;

$j(document).ready(function() {
	Workbench.initialize();
	Workbench.controls();
	Workbench.errors();
});

if (!window.Workbench) var Workbench = {};

Workbench.droppable = false;
Workbench.maskColor = '#fff';
Workbench.hideKey = 113;
Workbench.switchKey = 119;

Workbench.initialize = function()
{
	/* REINDEXING */
	
	$j('#catalog_product_attribute, #catalog_product_price, #catalog_url, #catalog_product_flat, #catalog_category_flat, #catalog_category_product, #catalogsearch_fulltext, #cataloginventory_stock, #tag_summary').bind('click', function(){
		if($j(this).hasClass('refresh')){
			var obj = $j(this);
			var index = obj.attr('id');
			obj.removeClass('refresh').addClass('processing');
			$j.post(reindexAllUrl, { id: index }, function(data) {
				obj.removeClass('processing').removeClass('require').addClass('refresh');
				console.log(data);
			});
		}
	});
	
	/* CACHE */
	/* Disable */
	$j('#config .status, #layout .status, #block_html .status, #translate .status, #collections .status, #eav .status, #config_api .status').bind('click', function(){
		if($j(this).hasClass('enabled')){
			var obj = $j(this);
			obj.removeClass('enabled').addClass('processing');
			var index = obj.parent().parent().attr('id');
			$j.post(disableCacheUrl, { types: [index] }, function(data) {
				obj.removeClass('processing').addClass('disabled');
				console.log(data);
			});
		}
	});
	
	/* Enable */
	$j('#config .status, #layout .status, #block_html .status, #translate .status, #collections .status, #eav .status, #config_api .status').bind('click', function(){
		if($j(this).hasClass('disabled')){
			var obj = $j(this);
			obj.removeClass('disabled').addClass('processing');
			var index = obj.parent().parent().attr('id');
			$j.post(enableCacheUrl, { types: [index] }, function(data) {
				obj.removeClass('processing').addClass('enabled');
				console.log(data);
			});
		}
	});

	/* Refresh */
	$j('#config .refresh, #layout .refresh, #block_html .refresh, #translate .refresh, #collections .refresh, #eav .refresh, #config_api .refresh').bind('click', function(){
		if($j(this).hasClass('refresh')){
			var obj = $j(this);
			obj.removeClass('refresh').addClass('processing');
			var index = obj.parent().parent().attr('id');
			$j.post(refreshCacheUrl, { types: [index] }, function(data) {
				obj.removeClass('processing').addClass('refresh');
				console.log(data);
			});
		}
	});
	
	/* Magento Cache Storage */
	$j('#magento-cache-storage').bind('click', function(){
		if($j(this).hasClass('static')){
			var obj = $j(this);
			obj.removeClass('static').addClass('processing');
			var index = obj.parent().parent().attr('id');
			$j.post(magentoCacheStorageUrl, { types: [index] }, function(data) {
				obj.removeClass('processing').addClass('static');
				console.log(data);
			});
		}
	});
	
	/* Cache storage */	
	$j('#cache-storage').bind('click', function(){
		if($j(this).hasClass('static')){
			var obj = $j(this);
			obj.removeClass('static').addClass('processing');
			var index = obj.parent().parent().attr('id');
			$j.post(flushAllUrl, { types: [index] }, function(data) {
				obj.removeClass('processing').addClass('static');
				console.log(data);
			});
		}
	});
	
	/* Catalog images cache */	
	$j('#catalog-images-cache').bind('click', function(){
		if($j(this).hasClass('static')){
			var obj = $j(this);
			obj.removeClass('static').addClass('processing');
			var index = obj.parent().parent().attr('id');
			$j.post(cleanImagesUrl, { types: [index] }, function(data) {
				obj.removeClass('processing').addClass('static');
				console.log(data);
			});
		}
	});
	
	/* Catalog css/js cache */	
	$j('#js-css-cache').bind('click', function(){
		if($j(this).hasClass('static')){
			var obj = $j(this);
			obj.removeClass('static').addClass('processing');
			var index = obj.parent().parent().attr('id');
			$j.post(cleanMediaUrl, { types: [index] }, function(data) {
				obj.removeClass('processing').addClass('static');
				console.log(data);
			});
		}
	});
	
	/* Clean var/cache */	
	$j('#cache-folder').bind('click', function(){
		if($j(this).hasClass('static')){
			var obj = $j(this);
			obj.removeClass('static').addClass('processing');
			$j.post(cleanVarUrl, function(data) {
				obj.removeClass('processing').addClass('static');
				console.log(data);
			});
		}
	});
	
	/* GET SYSTEM LOG */
	$j('#open-system-logs').live('click', function(){
		if(!$j(this).hasClass('processing')){
			$j(this).addClass('processing');
			$j(document).mask({ color: Workbench.maskColor, closeOnEsc: false, closeOnClick: false, opacity: 0.5 });
			$j.post(systemLogUrl, function(data){
				$j('#open-system-logs').removeClass('processing');
				$j('<div id="overlay" class="systemlog"></div>').appendTo('body');				
				$j('#overlay').html('<div class="file">' + data + '</div>').overlay({
					mask: {
						color: Workbench.maskColor,
						loadSpeed: 200,
						opacity: 0.5
					},
					load:true,
					closeOnClick:false,
					onClose: function(){
						$j('#overlay').remove();
					}
				});
			})
		}
	});
	
	/* PHP INFO */
	$j('#php-info').bind('click', function(){
		if(!$j(this).hasClass('processing')){
			$j('#php-info').addClass('processing');
			$j(document).mask({ color: Workbench.maskColor, closeOnEsc: false, closeOnClick: false, opacity: 0.5 });
			$j.post(phpInfoUrl, function(data){
				$j('<div id="overlay" class="phpinfo"></div>').appendTo('body');
				$j('#php-info').removeClass('processing');
				$j('#overlay').html(data).overlay({
					mask: {
						color: Workbench.maskColor,
						loadSpeed: 200,
						opacity: 0.5
					},
					load:true,
					closeOnClick:true,
					onClose: function(){
						$j('#overlay').remove();
					}
				});
			})
		}
	});
	
	/* DRAGGABLE DESIGN */
	$j('#design-file').draggable({
		stop: function(event, ui) {
			if($j('#design-file').draggable( 'option', 'helper' ) == 'clone' && Workbench.droppable){
				
				switch($j('#design-file').draggable( 'option', 'axis' ))
				{
					case 'x' : $j('#design-file').css( 'left', ui.offset.left ); break;
					case 'y' : $j('#design-file').css( 'top', ui.offset.top ); break;
					default : $j('#design-file').css( 'left' , ui.offset.left ); $j('#design-file').css( 'top', ui.offset.top ); break;
				}				
			}
			
			$j('#x-axis').val(ui.offset.left);
			$j('#y-axis').val(ui.offset.top);
			$j.cookie('x-axis', ui.offset.left, { path: '/' });
			$j.cookie('y-axis', ui.offset.top, { path: '/' });
		},
		drag: function(event, ui){
			$j('#x-axis').val($j('#design-file').position().left);
			$j('#y-axis').val($j('#design-file').position().top);
			$j.cookie('x-axis', $j('#design-file').position().left, { path: '/' });
			$j.cookie('y-axis', $j('#design-file').position().top, { path: '/' });
		}
	});
	
	if(Boolean(parseInt($j.cookie('toggler'))))
		$j('#design-file').fadeTo('slow', (($j.cookie('slider')) ? $j.cookie('slider') : 100) /100);
	
	/* Opacity slider */
	$j('#opacity-slider').slider({ range : "min", value : ($j.cookie('slider')) ? $j.cookie('slider') : 100, slide: function(event, ui) {
		var value = ui.value;
		$j('#design-file').fadeTo(0, value/100);
		$j.cookie('slider', value, { path: '/' });
		$j.cookie('toggler', 1, { path: '/' });
		$j('#design-selector .toggler').addClass('enabled');
	}});
	
	/* Snap to axis if cookie is set */
	if(Boolean(parseInt($j.cookie('snap'))))
	{
		var x = $j('#snap-to-grid #x-value').val();
		var y = $j('#snap-to-grid #y-value').val();
		$j('#design-file').draggable( "option", "grid", [x, y] );		
	}
	
	/* Snap to grid */
	$j('#snap-to-grid .icon').click(function(){
		//$j('#snap-to-grid .controls').toggle();
		
		if($j(this).hasClass('enabled')){
			$j(this).removeClass('enabled');
			$j('#design-file').draggable( "option", "grid", [1, 1] );
			$j.cookie('snap', 0, { path: '/' });
		}
		else{
			$j(this).addClass('enabled');
			
			var x = $j('#snap-to-grid #x-value').val();
			var y = $j('#snap-to-grid #y-value').val();
			$j.cookie('snap', 1, { path: '/' });
			$j('#design-file').draggable( "option", "grid", [x, y] );
		}
	});
	
	/* Snap axis controls */
	$j('#snap-to-grid input').keyup(function(e){
		if (!isNaN(parseInt(this.value,10))) {
			this.value = parseInt(this.value);
		} else {
			this.value = 0;
		}
		this.value = this.value.replace(/[^0-9]/g, '');
		
		var range = ($j(this).attr('id') == 'x-value') ? $j(window).width() : $j(window).height();
		
		if (parseInt(this.value,10) > range) {
			this.value = range;
			return;
		}
		
		var x = $j('#snap-to-grid #x-value').val();
		var y = $j('#snap-to-grid #y-value').val();
		
		($j(this).attr('id') == 'x-value') ? $j.cookie('snapx', x, { path: '/' }) : $j.cookie('snapy', y, { path: '/' });
	
		$j('#design-file').draggable( "option", "grid", [x, y] );	
	});
	
	/* Positioning */
	$j('#constrain input').keyup(function(e){
		if (!isNaN(parseInt(this.value,10))) {
			this.value = parseInt(this.value);
		} else {
			this.value = 0;
		}
		this.value = this.value.replace(/[^0-9]/g, '');
		
		var range = ($j(this).attr('id') == 'x-axis') ? $j(window).width() : $j(window).height();
		
		if (parseInt(this.value,10) > range) {
			this.value = range;
			return;
		}
		
		$j.cookie(($j(this).attr('id') == 'x-axis') ? 'x-axis' : 'y-axis', parseInt(this.value,10), { path: '/' });
		
		$j('#design-file').css(($j(this).attr('id') == 'x-axis') ? 'left' : 'top', parseInt(this.value,10));
	
	});
	
	/* Constrains controls */
	if($j('#constrain .x-axis').hasClass('locked'))
		$j('#design-file').draggable( "option", "axis", 'y' );
	else if($j('#constrain .y-axis').hasClass('locked'))
		$j('#design-file').draggable( "option", "axis", 'x' );
		
	$j('#constrain .axis').click(function(){
		if($j(this).hasClass('locked')){
			$j(this).removeClass('locked');
			$j('#design-file').draggable( "option", "axis", '' );
			$j.cookie('constrainxlock', 0, { path: '/' });
			$j.cookie('constrainylock', 0, { path: '/' });
		}else{
			$j(this).addClass('locked');
			
			if($j(this).hasClass('x-axis')){
				$j('#design-file').draggable( "option", "axis", 'y' );
				$j('#constrain .y-axis').removeClass('locked');
				$j.cookie('constrainxlock', 1, { path: '/' });
				$j.cookie('constrainylock', 0, { path: '/' });
				}
			else{
				$j('#design-file').draggable( "option", "axis", 'x' );
				$j('#constrain .x-axis').removeClass('locked');
				$j.cookie('constrainxlock', 0, { path: '/' });
				$j.cookie('constrainylock', 1, { path: '/' });
			}
		}
	});
	
	/* File sWitch */
	$j('#design-files').live('change', function(){
		$j('#design-file').attr('src', $j(this).val());
		$j.cookie('designimage', $j(this).val(), { path: '/' });
	});
	
	if(Boolean(parseInt($j.cookie('helper'))))
		$j('#design-file').draggable( "option", "helper", 'clone' );
		
	/* Helper */
	$j('#helper .icon').click(function(){
		$j('#helper .icon-drop').toggle();
		if($j(this).hasClass('enabled')){
			$j(this).removeClass('enabled');
			$j('#design-file').draggable( "option", "helper", 'original' );
			 $j.cookie('helper', 0, { path: '/' });
		}
		else{
			$j(this).addClass('enabled');
			$j('#design-file').draggable( "option", "helper", 'clone' );	
			$j.cookie('helper', 1, { path: '/' });			
		}
	});
	
	/* Enable/ Disable overlay image */
	$j('#design-selector .toggler').click(function(){
		$j('#design-selector .toggler').toggleClass('enabled');
		var value = Boolean(parseInt($j.cookie('toggler')));
		$j.cookie('toggler', value ? 0 : 1 , { path: '/' });
		if(value)
			$j('#design-file').fadeTo('slow', 0, function(){ $j(this).hide(); });
		else
			$j('#design-file').fadeTo('fast', (($j.cookie('slider')) ? $j.cookie('slider') : 100) /100);
			
	});
	
	if(Boolean(parseInt($j.cookie('helperdrop'))))
		Workbench.droppable = true;
	
	/* Helper: set as droppable */
	$j('#helper .icon-drop').click(function(){
		if($j(this).hasClass('enabled')){
			$j(this).removeClass('enabled');
			$j.cookie('helperdrop', 0, { path: '/' });
			Workbench.droppable = false;
		}
		else{
			$j(this).addClass('enabled');
			$j.cookie('helperdrop', 1, { path: '/' });
			Workbench.droppable = true;
		}
	});
	
	/* File upload controls */
	$j('.browse-file-input input').click(function(){
		$j('.custom-button.upload').show();
	});
	
	$j('.custom-button.upload').click(function(){
		$j('#submit-image').trigger('click');
	});
	
	/* Validate file upload form */
	$j('#fileform').ajaxForm(); // Init as ajax form
	
	var container = $j('.file-error');
	$j("#fileform").validate({
		errorContainer: container,
		meta: "validate"
	});
	
	/* Rescan web app for errors */
	$j('#refresh-logs').live('click', function(){
		$j('#errors').addClass('processing');
		$j('#errors .response').empty().load(errorUrl, function(){ $j('#errors').removeClass('processing'); });
	});
	
	/* Rescan script execution time on current page */
	$j('#exec-time').live('click', function(){
		if(!$j(this).hasClass('processing'));
			$j(this).addClass('processing').empty().load(executionUrl, { url: currentUrl }, function(){ $j(this).removeClass('processing'); });
	});
	
};

Workbench.errors = function()
{
	$j('#errors .response').load(errorUrl, function(){ $j(this).parent().removeClass('processing'); });
};

Workbench.controls = function()
{
	$j(document).keypress(function(e) {
		var keycode = e.keyCode ? e.keyCode : e.charCode;

		if(keycode == Workbench.hideKey){
			$j('#workbench').toggle();
			var value = Boolean(parseInt($j.cookie('controls')));
			$j.cookie('controls', value ? 0 : 1 , { path: '/' });
		}

		if(keycode == Workbench.switchKey){
			$j('.workbench-wrapper').toggleClass('bottom');
			$j('.workbench-wrapper').toggleClass('top');
			var value = Boolean(parseInt($j.cookie('wbposition')));
			$j.cookie('wbposition', value ? 0 : 1 , { path: '/' });
		}
	});
};

/* Is called after file upload in jquery.form.js:331 */
Workbench.updateSelectbox = function()
{
	$j('#design-selector').addClass('processing');
	$j('#design-files').hide();
	$j.post(designUrl, function(data){
		$j('#design-selector').removeClass('processing');
		$j('#design-files').after(data).remove();
	});
	$j('.file-error').hide();
};